package com.sdu.cloudservice;

import com.sdu.cloudservice.dao.SpiderHistoryDao;
import com.sdu.cloudservice.entity.SpiderHistoryEntity;
import com.sdu.cloudservice.service.GetPriceInfoService;
import com.sdu.cloudservice.service.InstanceService;
import com.sdu.cloudservice.service.SpiderStatus;
import com.sdu.cloudservice.util.DateUtil;
import com.sdu.cloudservice.util.EmailUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.Random;

/** 定时任务
 * Create by zekdot on 19-6-30.
 */
@Component
@Configuration
@EnableScheduling
public class ScheduleTask {

    @Autowired
    private GetPriceInfoService getPriceInfoService;
    @Autowired
    private SpiderHistoryDao spiderHistoryDao;
    //@Scheduled(cron = "* * 0/1 * * ?")
    @Scheduled(fixedRate = 3600000)
    private void checkSpider(){
//        try {
//            EmailUtil.send("zekdot@qq.com","检查是否需要运行爬虫");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        // 如果非演示模式并且爬虫正在工作
        if(!SpiderStatus.isShow && SpiderStatus.isWorking){
            return ;
        }
        // 如果之前已经工作或者间隔大于所规定的间隔
        try {
            // 如果刚刚启动程序
            if(SpiderStatus.workingEndTime.equals("")){
                SpiderHistoryEntity spiderHistoryEntity = spiderHistoryDao.getLastHistory();
                // 如果查出了最后时间
                if(spiderHistoryEntity != null){
                    SpiderStatus.workingEndTime = spiderHistoryEntity.getEndTime();
                    EmailUtil.send("zekdot@qq.com","设置新的最后工作时间为"+SpiderStatus.workingEndTime);
                }
            }

            if(DateUtil.getIntervalHours(DateUtil.str2DateTime(SpiderStatus.workingEndTime),new Date()) < SpiderStatus.fraquency){
                return ;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            try {
                EmailUtil.send("zekdot@qq.com","格式转换出现错误");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 进行爬取
        getPriceInfoService.updatePrice();
    }

    /**
     * 定时更新爬虫状态用于测试
     *
     *
     */
    @Autowired
    private InstanceService instanceService;

    @Scheduled(fixedRate = 5000)
    public void updateSpiderStatus(){
//        System.out.println("当前频率为" + SpiderStatus.fraquency);
//        JSONArray regions = JSONArray.fromObject(instanceService.getRegions().getObj());
//        for(Object region:regions){
//            // 转换成json对象
//            JSONObject jsonObject = JSONObject.fromObject(region);
//            System.out.print(jsonObject.getString("value") + "\t\t" + jsonObject.getString("level") + "\t");
//
//        }
//        System.out.println();




//  以下用于测试爬虫状态获取
        // System.out.println("运行");
        try {
            // 如果开启了演示模式
            if(SpiderStatus.isShow){
                SpiderStatus.isWorking = true;
                JSONArray regions = JSONArray.fromObject(instanceService.getRegions().getObj());
                Random random = new Random();
                int curRegionNum = random.nextInt(regions.size());
                JSONObject region = JSONObject.fromObject(regions.get(curRegionNum));
                SpiderStatus.curRegion = region.getString("value");
                SpiderStatus.curRegionProgress[0] = curRegionNum;
                SpiderStatus.curRegionProgress[1] = regions.size();

                JSONArray zones = JSONArray.fromObject(instanceService.getZoneByRegionId(region.getString("id")).getObj());
                int curZoneNum = random.nextInt(zones.size());
                JSONObject zone = JSONObject.fromObject(zones.get(curZoneNum));
                SpiderStatus.curZone = zone.getString("value");
                SpiderStatus.curZoneProgress[0] = curZoneNum;
                SpiderStatus.curZoneProgress[1] = zones.size();

                JSONArray instances = JSONArray.fromObject(instanceService.getInstanceByZoneId(zone.getString("id")).getObj());
                JSONObject instance = JSONObject.fromObject(instances.get(curZoneNum));
                int curInstanceNum = random.nextInt(instances.size());
                SpiderStatus.curInstance = instance.getString("value");
                SpiderStatus.curInstanceProgress[0] = curInstanceNum;
                SpiderStatus.curInstanceProgress[1] = instances.size();
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        // System.out.println("当前" + SpiderStatus.curRegion + " " + SpiderStatus.curZone + " " + SpiderStatus.curInstance);

    }

}
